<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 后台评论输出组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Comments_Ucenter extends Widget_Abstract_Comments
{
	
    /**
     * 内容个数
     *
     * @access private
     * @var integer
     */
    protected $_total = false;

    /**
     * 当前页
     *
     * @access private
     * @var integer
     */
    protected $_currentPage = 1;

    /**
     * 获取菜单标题
     *
     * @return string
     * @throws Widget_Exception
     */
    public function getMenuTitle()
    {
        $content = $this->parentContent;

        if ($content) {
            return _t('%s的评论', $content['title']);
        }

        throw new Widget_Exception(_t('内容不存在'), 404);
    }

    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
		$this->user->pass('contributor');
		
        $select = $this->select();
        $this->parameter->setDefault('pageSize=20');
        $this->_currentPage = $this->request->get('page', 1);

        /** 过滤标题 */
        if (NULL != ($keywords = $this->request->filter('search')->keywords)) {
            $select->where('table.comments.text LIKE ?', '%' . $keywords . '%');
        }

        /** 如果具有编辑以上权限,可以查看所有文章,反之只能查看自己的文章 */
        if (!$this->user->pass('editor', true)) {
            $select->where('table.comments.uid = ?', $this->user->uid);
        } else {
			
			if (isset($this->request->uid)) {
                $select->where('table.comments.uid = ?', $this->request->filter('int')->uid);
			} else if('off' == $this->request->all){
                $select->where('table.comments.uid = ?', $this->user->uid);
			}
		}	

        //增加按文章归档功能
        if (isset($this->request->cid)) {
            $select->where('table.comments.cid = ?', $this->request->filter('int')->cid);
        }

		/** 计算数目 */
		$this->_total = (clone $select)
            ->select(array('COUNT(*)' => 'num'))
            ->fetchObject()->num;

        $select->order('table.comments.coid', 'DESC')
        ->page($this->_currentPage, $this->parameter->pageSize);

        $select->fetchAll(array($this, 'push'));
    }

    /**
     * 输出分页
     *
     * @access public
     * @return void
     */
    public function pageNav()
    {
        $query = $this->request->makeUriByRequest('page={page}');

        /** 使用盒状分页 */
        $nav = new Page_Box($this->_total,
        $this->_currentPage, $this->parameter->pageSize, $query);
        return $nav->render('&laquo;', '&raquo;');
    }
	
    public function commentList()
    {
		$this->widget('Widget_Metas_Category_List')->to($category);

        $html = '
		<form method="get">
		    <div class="cola-search">';

		if($this->user->pass('editor', true) && !isset($this->request->uid)){	
            $html .= '<select name="all">
                <option value="on"'.((null === $this->request->all || 'on' == $this->request->all) ? ' selected="true"' : '') .'>'._t('所有').'</option>
                <option value="off"'.('off' == $this->request->all ? ' selected="true"' : '') .'>'._t('我的').'</option>';
            $html .= '</select> ';
		}	
        $html .= '<input type="text" placeholder="'._t('请输入关键字').'" value="'. htmlspecialchars($this->request->keywords).'" name="keywords" />';

        if ('' != $this->request->keywords || '' != $this->request->uid || '' != $this->request->all){
            $html .= '<a class="cola-search-cancel ci-cancel" href="'.$this->options->ucenterUrl('comments', false).'"></a>';
	    }
        if(isset($this->request->uid)){
            $html .= '<input type="hidden" value="'.htmlspecialchars($this->request->uid).'" name="uid" />';
        }
        $html .= '</div></form>';

        if ($this->have()) {
			$Layout = new Layout();
			$Layout->addClass('cola-comments')->setAttr('id', 'cola-comments');
			$Layout->header(array(
				$this->widget('Widget_Comments_Edit')->operate(),
			    _t('作者'),
				_t('内容'),
			));

			while ($this->next()){
				
			    $Layout->append(
				
	    '<div class="cola-lists cola-commentList" data-coid="'.$this->coid .'">
			<div class="cola-commentHeader">
                <img src="'. $this->author->avatar .'" width="40" height="40"/>
				<div class="cola-commentInfo"><a href="'. $this->request->makeUriByRequest('uid=' . $this->uid) .'">'.$this->author->name .'</a>
                ' . ($this->author->mail ? '<span><a href="mailto:'.$this->author->mail.'">'.$this->author->mail.'</a></span>' : '')  . ($this->author->ip ? '<span>'.$this->author->ip .'</span>' : '') . '
				</div>
			</div>
            <div class="cola-commentBody" data-text="'.htmlspecialchars(Json::encode($this->text)).'">
                <div class="cola-commentLink">'. $this->dateWord .' 于 <a href="'. $this->request->makeUriByRequest('cid=' . $this->cid) .'">'.$this->title .'</a>&nbsp;&nbsp;&nbsp;<a href="'.$this->permalink.'"><i class="ci-link"></i></a></div>
                <div class="cola-comment-content">'. $this->content .'</div> 
                <div class="cola-action hidden-by-mouse">
                    <a href="#'.$this->theId .'" data-url="'.$this->security->actionUrl('comments-edit?do=update&coid=' . $this->coid, false).'" class="cola-edit" data-cancel='._t('取消').'>'._t('编辑').'</a>

                    <a href="#'.$this->theId.'" data-url="'.$this->security->actionUrl('comments-edit?do=reply&coid=' . $this->coid, false).'" class="cola-reply" data-cancel='._t('取消').'>'._t('回复').'</a>

                    <a data-delete="'._t('删除').'" data-confirm="'._t('确认删除 %s 的评论', $this->author->name).'" href="'.$this->security->actionUrl('comments-edit?do=delete&coid=' . $this->coid, false).'" class="cola-delete">'._t('删除').'</a>
                </div>
            </div>
		</div>'
				);

		    }
			$Layout->append('<ul class="cola-pager">' . $this->pageNav() . '</ul>');

			$html .= $Layout->render();

        $this->widget('Widget_Scripts')->set(
<<<EOF
(function () {
    $(document).ready(function () {
		
		var comments = $('#cola-comments');
		comments.on('click', '.cola-delete', function() {
		    var t  = $(this), 
            deletetext = t.html(),
			confirmtext = t.data('confirm'),	
			url        = t.attr('href'), 
			list       = t.parents('.cola-commentList'), 
			coid       = t.data('coid'),
			num        = t.data('num');
			
			if(!num) { 
			    t.data('num', 1);
				t.html(confirmtext);
				setTimeout(function(){
					t.data('num', 0);
					t.html(deletetext);
				}, 2000);
			    return false;
			}
			t.html('loading..');
			$.xpost(url, function(code, message, data) {
                if(code == 0){
					list.fadeOut(function () {
                        list.remove();
                    });
				    !comments.find('.cola-commentList').length && setTimeout(function(){
				        window.location.reload();
			        }, 1500);
				} else {
					$.alert(message);
				}
				t.html(deletetext);
		    });
			return false;
        });
				
		comments.on('click', '.cola-reply', function(e) {
            var t = $(this),
            replytext = t.html(),
			canceltext = t.data('cancel'),
			url = t.data('url'), 
			action = t.parent('.cola-action'),
			body = t.parents('.cola-commentBody'),
			content = body.find('.cola-comment-content'),
            form = $('<div class="cola-comment-form"><p><textarea class="cola-comment-textarea" name="text" rows="3"></textarea></p><p><a class="cola-button text-md cola-comment-reply">'+replytext+'</a> <a class="cola-button text-md cola-comment-cancel">'+canceltext+'</a></p></div>'),
			textarea = form.find('.cola-comment-textarea'),
			reply = form.find('.cola-comment-reply'),
			
			cancel = form.find('.cola-comment-cancel');
			form.insertBefore(action);
			action.hide();
			textarea.focus();
			cancel.click(function(e) {
			    form.remove();
				action.show();
			});

			reply.click(function(e) {
				
				var text = textarea.val();
				
				if(text == '') {
					textarea.focus();
				    return false;
				}
				reply.html('loading..');
			    $.xpost(url, {text: text}, function(code, message, data) {
                    if(code == 0){
						action.before('<div class="cola-reply-text">'+message.text+'</div>');
						form.remove();
				    } else {
					    $.alert(message);
				    }
					action.show();
				    reply.html(replytext);
		        });
			});

            return false;
        });
				
				
		comments.on('click', '.cola-edit', function(e) {
            var t = $(this), 
            edittext = t.html(),
			canceltext = t.data('cancel'),
			url = t.data('url'), 
			action = t.parent('.cola-action'),
			body = t.parents('.cola-commentBody'),
			content = body.find('.cola-comment-content'),
			form = $('<div class="cola-comment-form"><p><textarea class="cola-comment-textarea" name="text" rows="3"></textarea></p><p><a class="cola-button text-md cola-comment-edit">'+edittext+'</a> <a class="cola-button text-md cola-comment-cancel">'+canceltext+'</a></p></div>'),
			textarea = form.find('.cola-comment-textarea'),
			edit = form.find('.cola-comment-edit'),
			cancel = form.find('.cola-comment-cancel');
			form.insertBefore(content);
			textarea.height(content.height()).html(content.html()).focus();
			action.hide();
			content.hide();
			cancel.click(function(e) {
			    form.remove();
				content.show();
				action.show();
			});
			
			edit.click(function(e) {
				var text = textarea.val();
				if(text == '' || text == content.html()) {
					textarea.focus();
				    return false;
				}
				edit.html('loading..');
			    $.xpost(url, {text: text}, function(code, message, data) {
                    if(code == 0){
						content.html(message.text);
						form.remove();
				    } else {
					    $.alert(message);
				    }
			        edit.html(edittext);
					content.show();
					action.show();
		        });
			});
            return false;
        });		

    });
})();
EOF
			);

		}

		return $html;
	}

}
